<template>
  <d-layout style="height: 100%">
    <d-aside class="daside">
      <div class="sideLogo">
        <img src="../assets/devui-logo.svg">
        <span>DevUI Admin</span>
      </div>
      <d-menu style="height: 100%;" :collapsed-indent="48" mode="vertical" width="240px" :default-select-keys="['MateChat']">
        <d-menu-item key="MateChat">
          <template #icon>
            <i class="icon-homepage"></i>
          </template>
          <span>MateChat 演示</span>
        </d-menu-item>
      </d-menu>
    </d-aside>
    <d-layout style="overflow: auto">
      <d-header class="dheader">
        <Header @openDrawer="openDrawer()" class="page-header" :drawerOpen="visible"></Header>
      </d-header>
      <d-content class="main-content">
        <Content></Content>
        <Footer></Footer>
      </d-content>
    </d-layout>
  </d-layout>
  <d-drawer v-model="visible" position="right" style="padding: 20px; width: 650px" :show-overlay="false" :close-on-click-overlay="false">
    <keep-alive>
      <Demo @closeDrawer="visible = false" @chartStrChange="chartStrChange($event)"/>
    </keep-alive>
  </d-drawer>
</template>

<script>
import { defineComponent, ref, onMounted, onUnmounted, createApp } from 'vue'
import Content from './Content.vue'
import Header from './Header.vue';
import Footer from './Footer.vue';
import Demo from './MateChat/Demo.vue';
import SimpleDemo from './MateChat/SimpleDemo.vue';
import { loadModule } from 'vue3-sfc-loader';
import VChart from 'vue-charts';

export default defineComponent({
  components: {
    Content, Header, Footer, Demo, SimpleDemo
  },

  setup() {
    const openDrawer = () => {
      visible.value = true;
    }
    const menu = ref([
      {
        title: 'Dashboard',
        open: true,
        children: [{ title: 'MateChat Demo' }],
      },
    ])

    const chartStr = ref('');

    const visible = ref(false);

    // 拖动事件监听
    const isDragging = ref(false);
    const position = ref({ x: 0, y: 0 });

    const chartStrChange = (event) => {
      chartStr.value = event;
    }

    const handleDragOver = (e) => {
      e.preventDefault();
      if (isDragging.value) {
        position.value = {
          x: e.clientX,
          y: e.clientY
        };
      }
    };

    const handleDrop = (e) => {
      e.preventDefault();
      const randomId = `chart-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
  
      // 获取拖动的数据
      const draggedHTML = e.dataTransfer.getData('text/html');
      
      // 获取放下位置的元素
      const dropTarget = document.elementFromPoint(e.clientX, e.clientY);
      const nearestContentCard = dropTarget?.closest('.devui-col');

      if (nearestContentCard) {
        // 创建新的元素
        const newCard = document.createElement('div');
        newCard.className = nearestContentCard.className;
        // 使用拖动元素的内容
        if (nearestContentCard.offsetHeight > 300) {
          newCard.innerHTML = `<div class='content-card'><div class='chart-card'id='${randomId}'></div></div>`;
        } else {
          newCard.innerHTML = `<div class='content-card-sm'><div class='chart-card'id='${randomId}'></div></div>`;
        }
        
        // 将新元素插入到目标元素之前
        nearestContentCard.parentNode.insertBefore(newCard, nearestContentCard);
        nearestContentCard.remove();
      }
      
      isDragging.value = false;

      createChart(randomId);
    };

    onMounted(() => {
      document.addEventListener('dragover', handleDragOver);
      document.addEventListener('drop', handleDrop);
    });

    onUnmounted(() => {
      document.removeEventListener('dragover', handleDragOver);
      document.removeEventListener('drop', handleDrop);
    });

    // 预处理组件字符串，移除 import 语句
    const processComponentString = (str) => {
      str = str.replace(/import.*from.*['"]vue-echarts['"];?\n?/g, '');
      str = str.replace(/import.*from.*['"]echarts['"];?\n?/g, '');
      str = str.replace(/components:\s*{\s*VChart,?\s*},?/g, '');
      str = str.replace(/<v-chart/g, '<vue-echarts');
      str = str.replace(/<\/v-chart>/g, '</vue-echarts>');
      return str
    };


    const createChart = async (id) => {
      const options = {
        moduleCache: {
            vue: Vue
        },
        getFile(url) {
            if (url === 'file.vue') {
                const processedStr = processComponentString(chartStr.value);
                return Promise.resolve(processedStr)
            }
        },
        addStyle(textContent) {
            const style = document.createElement('style');
            style.textContent = textContent;
            document.head.appendChild(style);
            return style;
        },
        handleModule: async (type, source, path, options) => {
            if (type === '.vue') {
                return Vue.defineComponent(source.default);
            }
        }
        };

        // 加载组件
        const component = await loadModule('file.vue', options);
        // 创建新实例
        const app = createApp(component).component('vue-echarts', VChart);

        app.config.globalProperties.$echarts = echarts;
        app.config.globalProperties.echarts = echarts;

        app.mount(`#${id}`);
    }
    return {
      menu, openDrawer, visible, createChart, chartStrChange
    }
  }
})

</script>

<style lang="scss" scoped>
@use 'devui-theme/styles-var/devui-var.scss' as *;

.floating-card {
  position: fixed;
  transform: translate(-50%, -50%);
  pointer-events: none;
  opacity: 1;
  z-index: 9999;
}

.daside {
  display: flex;
  flex-direction: column;
  z-index: 21;
  background-color: $devui-base-bg;;
  width: 240px;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: var(--devui-shadow-length-connected-overlay, 0 2px 12px 0) var(--devui-light-shadow, rgba(37, 43, 58, 0.12));
}

.dheader {
  z-index: 20;
  position: fixed;
  width: calc(100%);
}

.dfooter {
  text-align: center;
  line-height: 40px;
  min-height: 40px;
}

.main-content {
  flex: 1;
  margin-top: 60px;
  text-align: center;
  padding: 12px;
}

.page-header {
  border-bottom: 1px solid $devui-dividing-line;
  box-shadow: var(--devui-shadow-length-connected-overlay, 0 2px 4px) var(--devui-light-shadow, rgba(37, 43, 58, 0.12));
}

.sideLogo {
  display: flex;
  align-items: center;
  cursor: pointer;
  width: 100%;
  height: 80px;
  padding-left: 16px;
  gap: 8px;
  span {
    font-size: var(--devui-font-size-modal-title, 18px);
    font-weight: 600;
    white-space: nowrap;
  };
  img {
    height: 30px;
    width: 30px;
  };
}

</style>